const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const superagent = require('superagent');
require("superagent-charset")(superagent);
const dayjs = require("dayjs");
const ww = require('chinese-workday');

const tuyere = require('../model/tuyere');


async function getTuyeres(){


    if (!ww.isWorkday(dayjs().format("YYYY-MM-DD"))){
        return null;
    }

     let result = await superagent.get("https://push2.eastmoney.com/api/qt/clist/get")
        .set('user-agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36')
        .set('Content-Type','application/json')
        .query({
            fs: "m:90+e:2",
            fields: "f1,f12,f13,f14,f3,f62,f2,f3,f605",
            fid: "f62",
            po: 1,
            pn: 1,
            pz: 100,
            np: 1,
            fltt: 2,
            invt: 2,
            ut: "f057cbcbce2a86e2866ab8877db1d059"
        })

        return result.body;
}



router.post('/excute',(req,res)=>{

    getTuyeres().then(async result=>{

        if (!result){
            res.send({
                code: 1,
                msg: "今天休息"
            })
            return;
        }


        const date = new Date(dayjs().format('YYYY-MM-DD'));

        let model = {};


        try {

            const row = await tuyere.tuyereModel.findOne({date: {$eq: date}}).select("date");


            result.data.diff.forEach(a=>{

                tuyere.tuyereSchema.path(a.f12,{
                    type: Number,
                    require: true
                });

                model[a.f12] = a.f62;
            })



            if (row){
                console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'),'更新数据')

                await tuyere.tuyereModel.findByIdAndUpdate(row._id.toString(),{$set: model},{ new: true,runValidators: true });

            } else {

                console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'),'新增数据')
                await tuyere.tuyereModel.create({
                    date,
                    ...model
                })

            }

        } catch (e){

            console.error(e)

            res.send({
                code: 1,
                msg: e.toString()
            })


            return;

        }

        res.send({
            code: 0,
            data: {
                title: dayjs(date).format('YYYY-MM-DD'),
                chart: model
            }
        })

    })


})


router.get('/find',async (req,res)=>{


    let date = new Date(dayjs().format('YYYY-MM-DD'));

    if (req.query.date){
        date = new Date(req.query.date);
    }


    let response = {
        code: 0,
        data: {

        }
    }

    try{
        let row = await tuyere.tuyereModel.findOne({date: {$eq: date}}).select("-date -_id -__v")

        response.data = {
            title: dayjs(date).format('YYYY-MM-DD'),
            chart: row
        };
    } catch(err){
        console.error(err)
        response.code = 1;
    }


    res.send(response)



})


module.exports = router;
